class ProjectController {
    
	def scaffold = Project

	def home = {        
		if(!params.max) params.max = 10
        	[ projectList: Project.list( params ) ]
		}
	def group = {}
	
	def projectByDetails ={
			def projectDetails = Project.get(params.projectTitleId)
			return [project : projectDetails]
	}

	def save = {
			
		def project = new Project (params)
		if (session.user.role.name == 'Student') {
			project.student = session.user

			Project chosenProject = session.user.chosenProject()
			if (chosenProject != null) {
				chosenProject.student = null
				chosenProject.save()
			}
		}
		if (!project.hasErrors() && project.save()) {
			flash.message = "Project ${project.projectName} is created"
			redirect(action:show, id:project.id)
		}
		else {
			render(view:'create', model:[project:project])
		}
	}

	def list = {
		if(!params.max) params.max = 10
		if(!params.projectGroupId){
			if(session.user.role.name == "Supervisor" |session.user.role.name == "Organiser"){
				return [projectList: Project.findAllWhere(supervisor: session.user)]
		}
		}
	 	else return [projectList: Project.findAllWhere(group: ProjectGroup.get(params.projectGroupId))]
	}	

	def choose = {
		// If the user click "Choose" without selecting a projet
		if (!params.projectChoice) {
			flash.message = "Please select a project before you click \"Choose\""
            		redirect(action:"list", params:["projectGroupId":params.projectGroupId]) 
		}
		else {
			// If has previous project selection, then remove it
			def tProject = session.user.chosenProject()
			if (tProject) {
				tProject.student = null
				tProject.save()	
			}
			
			// save the new project choice
			def project = Project.get(params.projectChoice)
			project.student = session.user
        		if(!project.hasErrors() && project.save()) {
            			flash.message = "You have chosen ${project.projectName} " 
            			redirect(action:"list", controller:"projectGroup")
	        	}
        		else {
            			flash.message = "Project -- ${project.projectName} is not chosen succesfully"
           			redirect(action:list)
	        	}
		}
	}
}

